package com.blrs.service.project.review.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.domain.*;
import com.blrs.mapper.*;
import com.blrs.service.project.review.IProjectReviewInfoService;
import com.blrs.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-05
 */
@Service
public class ProjectReviewInfoServiceImpl implements IProjectReviewInfoService {
    @Autowired
    private ProjectReviewInfoMapper projectReviewInfoMapper;
    @Autowired
    private ProjectInfoMapper projectInfoMapper;
    @Autowired
    private SubProjectInfoMapper subProjectInfoMapper;
    @Autowired
    private PurchasingMapper purchasingMapper;
    @Autowired
    private EnterpriseInfoMapper enterpriseInfoMapper;
    @Autowired
    private ReceivableMapper receivableMapper;
    @Autowired
    private ContractManagementInfoMapper contractManagementInfoMapper;
    @Autowired
    private ProjectPaymentMethodMapper projectPaymentMethodMapper;
    @Autowired
    private ProjectBudgetMapper projectBudgetMapper;
    @Autowired
    private CostControlMapper costControlMapper;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询【请填写功能名称】
     *
     * @param reviewId 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public ProjectReviewInfo selectProjectReviewInfoByReviewId(String reviewId) {
        return projectReviewInfoMapper.selectProjectReviewInfoByReviewId(reviewId);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param projectReviewInfo 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<ProjectReviewInfo> selectProjectReviewInfoList(ProjectReviewInfo projectReviewInfo) {
        return projectReviewInfoMapper.selectProjectReviewInfoList(projectReviewInfo);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param projectReviewInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertProjectReviewInfo(ProjectReviewInfo projectReviewInfo) {
        ProjectInfo projectInfo = projectInfoMapper.selectProjectInfoByProjectId(projectReviewInfo.getProjectId());
        if ("0".equals(projectInfo.getState()) && "0".equals(projectInfo.getSign())) {
            projectReviewInfoMapper.deleteContractReviewInfoByProjectId(projectReviewInfo.getProjectId());
        }
        //如果当前最新的一条评审结果为空，说明该数据还没有被评审，不能一直重复添加评审数据
        int count=projectReviewInfoMapper.selectCountByProjectId(projectReviewInfo.getProjectId());
        projectInfo.setCovenantId(projectReviewInfo.getReviewerId().toString());
        projectInfo.setContractReviewer(projectReviewInfo.getReviewer());
        projectInfoMapper.updateProjectInfo(projectInfo);
        if (count > 0){
            //说明项目已经有最新的审核人，无需再添加，修改即可
            return projectReviewInfoMapper.updateProjectReviewInfoByProjectId(projectReviewInfo);
        }else {
            return projectReviewInfoMapper.insertProjectReviewInfo(projectReviewInfo);
        }
    }

    @Override
    public int addProjectReviewInfo(ProjectReviewInfo projectReviewInfo) {
        int count = 0;
        ProjectReviewInfo reviewInfo = new ProjectReviewInfo();
        reviewInfo.setProjectId(projectReviewInfo.getProjectId());
        List<ProjectReviewInfo> reviewInfoList = projectReviewInfoMapper.selectProjectReviewInfoList(reviewInfo);
        for (int i = 0; i < reviewInfoList.size(); i++) {
            if (StringUtils.isEmpty(reviewInfoList.get(i).getReviewResult())) {
                ProjectReviewInfo info = projectReviewInfoMapper.selectProjectReviewInfoByReviewId(reviewInfoList.get(i).getReviewId());
                info.setReviewComments(projectReviewInfo.getReviewComments());
                info.setReviewResult(projectReviewInfo.getReviewResult());
                info.setReviewTime(new Timestamp(new Date().getTime()));
                count = projectReviewInfoMapper.updateProjectReviewInfo(info);
            }
        }
        if ("0".equals(projectReviewInfo.getReviewResult())) {
            ProjectInfo projectInfo = projectInfoMapper.selectProjectInfoByProjectId(projectReviewInfo.getProjectId());
            //String reviewer = projectInfo.getContractReviewer() == null ? "" : projectInfo.getContractReviewer() + ",";
  //          projectInfo.setCovenantId(projectInfo.getCovenantId() + "," + projectInfo.getReviewerId());
//            if (StringUtils.isNotEmpty(projectInfo.getContractReviewer())) {
//                projectInfo.setContractReviewer(projectInfo.getContractReviewer());
//                if (projectInfo.getContractReviewer().indexOf(projectReviewInfo.getReviewer()) != -1) {
//                    String newReviewer = projectInfo.getContractReviewer().replace(projectReviewInfo.getReviewer(), "");
//                    projectInfo.setContractReviewer(newReviewer);
//                } else {
//                    projectInfo.setContractReviewer(projectInfo.getContractReviewer() +SecurityUtils.getLoginUser().getUser().getNickName());
//                }
//            } else {
//                if (projectReviewInfo.getReviewer().equals(SecurityUtils.getLoginUser().getUser().getNickName())) {
//                    projectInfo.setContractReviewer("");
//                } else {
//                    projectInfo.setContractReviewer(reviewer + SecurityUtils.getUsername());
//                }
//            }
            if (StringUtils.isNotEmpty(projectInfo.getContractReviewer())){
                projectInfo.setContractReviewer(projectReviewInfo.getReviewer());
                projectInfo.setCovenantId(projectReviewInfo.getReviewerId().toString());
            }
            projectInfoMapper.updateProjectInfo(projectInfo);
            ProjectReviewInfo review = new ProjectReviewInfo();
            review.setReviewId(projectReviewInfo.getReviewId());
            review.setProjectId(projectReviewInfo.getProjectId());
            review.setReviewerId(projectReviewInfo.getReviewerId());
            review.setReviewer(projectReviewInfo.getReviewer());
            count = projectReviewInfoMapper.insertProjectReviewInfo(review);
        }
        if ("1".equals(projectReviewInfo.getReviewResult())) {
            ProjectInfo projectInfo = projectInfoMapper.selectProjectInfoByProjectId(projectReviewInfo.getProjectId());
            projectInfo.setSign("1");
            projectInfo.setState("0");
            projectInfo.setContractReviewer(null);
            projectInfo.setCovenantId(null);
            projectInfoMapper.updateProjectInfo(projectInfo);
            SubProjectInfo info = new SubProjectInfo();
            info.setProjectId(projectReviewInfo.getProjectId());
            List<SubProjectInfo> projectInfoList = subProjectInfoMapper.selectSubProjectInfoList(info);
            for (int i = 0; i < projectInfoList.size(); i++) {
                SubProjectInfo subProjectInfo = projectInfoList.get(i);
                subProjectInfo.setState("0");
                subProjectInfoMapper.updateSubProjectInfo(subProjectInfo);
            }
        }
        if ("2".equals(projectReviewInfo.getReviewResult())) {
            ProjectInfo projectInfo = projectInfoMapper.selectProjectInfoByProjectId(projectReviewInfo.getProjectId());
            projectInfo.setState("2");
            projectInfo.setSign("2");
            projectInfo.setContractReviewer(null);
            projectInfo.setCovenantId(null);
            projectInfoMapper.updateProjectInfo(projectInfo);
            SubProjectInfo info = new SubProjectInfo();
            info.setProjectId(projectReviewInfo.getProjectId());
            List<SubProjectInfo> projectInfoList = subProjectInfoMapper.selectSubProjectInfoList(info);
            for (int i = 0; i < projectInfoList.size(); i++) {
                SubProjectInfo subProjectInfo = projectInfoList.get(i);
                subProjectInfo.setState("2");
                subProjectInfoMapper.updateSubProjectInfo(subProjectInfo);
            }
            //写入采购合作记录
            SubProjectInfo subProjectInfo1 = new SubProjectInfo();
            subProjectInfo1.setProjectId(projectReviewInfo.getProjectId());
            EnterpriseInfo enterpriseInfo = enterpriseInfoMapper.selectEnterpriseInfoByEnterpriseId(projectInfo.getEnterpriseId());
            List<SubProjectInfo> infos = subProjectInfoMapper.selectSubProjectInfoList(subProjectInfo1);
            for (int a = 0; a < infos.size(); a++) {
                Purchasing purchasing = new Purchasing();
                purchasing.setId(UUID.randomUUID().toString());
                purchasing.setPurchasingNo(getTicketIdByTime());
                purchasing.setProjectId(projectReviewInfo.getProjectId());
                purchasing.setEstablishTime(new Timestamp(new Date().getTime()));
                purchasing.setOutsourcingId(infos.get(a).getOutsourcingId());
                purchasing.setSupplier(infos.get(a).getOutsourcingCompany());
                purchasing.setEnterpriseName(projectInfo.getEnterpriseName());
                purchasing.setProjectNo(infos.get(a).getProjectNumber());
                purchasing.setProjectName(infos.get(a).getProjectName());
                purchasing.setPlanTime(infos.get(a).getStartTime());
                purchasing.setCompleteTime(infos.get(a).getEndTime());
                purchasing.setFee(new BigDecimal(infos.get(a).getCost()));
                purchasing.setStatus("2");
               if (Objects.nonNull(enterpriseInfo)){
                   if (StringUtils.isNotEmpty(enterpriseInfo.getBankName())){
                       purchasing.setBankName(enterpriseInfo.getBankName());
                   }
                   if (StringUtils.isNotEmpty(enterpriseInfo.getBankNo())){
                       purchasing.setBankNo(enterpriseInfo.getBankNo());
                   }
               }
                purchasing.setCreationTime(new Timestamp(new Date().getTime()));
                purchasing.setOperateTime(new Timestamp(new Date().getTime()));
                purchasing.setOperateId(SecurityUtils.getUserId());
                purchasing.setOrganizationId(SecurityUtils.getOrgId());
                purchasing.setOrganizationName(SecurityUtils.getOrgName());
                purchasing.setDepartmentId(SecurityUtils.getDeptId());
                purchasing.setDepartmentName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
                if ("0".equals(infos.get(a).getType())) {
                    purchasing.setIsCooperate("0");
                } else if ("1".equals(infos.get(a).getType())) {
                    purchasing.setIsCooperate("1");
                }
                purchasingMapper.insertPurchasing(purchasing);
            }
            //生成应收管理记录
            ProjectPaymentMethod paymentMethod = new ProjectPaymentMethod();
            paymentMethod.setProjectId(projectReviewInfo.getProjectId());
            List<ProjectPaymentMethod> paymentMethods = projectPaymentMethodMapper.selectProjectPaymentMethodList(paymentMethod);
            for (int i = 0; i < paymentMethods.size(); i++) {
                Receivable receivable = new Receivable();
                receivable.setId(UUID.randomUUID().toString());
                receivable.setProjectId(projectReviewInfo.getProjectId());
                receivable.setProjectName(projectInfo.getProjectName());
                receivable.setContractId(projectInfo.getContractId());
                receivable.setContractName(projectInfo.getContractName());
                receivable.setCusId(projectInfo.getEnterpriseId());
                receivable.setCusName(projectInfo.getEnterpriseName());
                if (StringUtils.isNotEmpty(projectInfo.getContractId())) {
                    ContractManagementInfo contractManagementInfo = contractManagementInfoMapper.selectContractManagementInfoByContractId(projectInfo.getContractId());
                    receivable.setContractNumber(contractManagementInfo.getContractNumber());
                }
                receivable.setClassificationId("650c44e1-b575-4b62-9d54-1ba9d1e8abb7");
                receivable.setEstimatedCollectionTime(paymentMethods.get(i).getEstimatedCollectionTime());
                receivable.setAmount(paymentMethods.get(i).getAmountCollected());
                receivable.setPayment(paymentMethods.get(i).getPaymentName());
                receivable.setStatus("0");
                receivable.setCreationId(SecurityUtils.getUserId());
                receivable.setCreationName(SecurityUtils.getUsername());
                receivable.setCreationTime(new Timestamp(new Date().getTime()));
                receivable.setOperateTime(new Timestamp(new Date().getTime()));
                receivable.setOperateId(SecurityUtils.getUserId());
                receivable.setOrganizationId(SecurityUtils.getOrgId());
                receivable.setOrganizationName(SecurityUtils.getOrgName());
                receivable.setBelongTo(SecurityUtils.getOrgId());
                receivable.setDepartmentName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
                receivableMapper.insertReceivable(receivable);
            }
            //生成成本管理记录
            ProjectBudget budget = new ProjectBudget();
            budget.setProjectId(projectReviewInfo.getProjectId());
            List<ProjectBudget> budgetList = projectBudgetMapper.selectProjectBudgetList(budget);
            if(budgetList!=null){
                for (int i = 0; i < budgetList.size(); i++) {
                    CostControl cost = new CostControl();
                    cost.setId(UUID.randomUUID().toString());
                    cost.setClassificationId("650c44e1-b575-4b62-9d54-1ba9d1e8abb7");
                    cost.setSource("0");//项目管理
                    cost.setContractId(projectInfo.getContractId());
                    if (StringUtils.isNotEmpty(projectInfo.getContractId())) {
                        ContractManagementInfo contractManagementInfo = contractManagementInfoMapper.selectContractManagementInfoByContractId(projectInfo.getContractId());
                        cost.setContractNo(contractManagementInfo.getContractNumber());
                    }
                    cost.setProjectId(projectReviewInfo.getProjectId());
                    cost.setProjectName(projectInfo.getProjectName());
                    cost.setStatus("0");
                    cost.setDepartmentId(SecurityUtils.getDeptId());
                    cost.setDepartmentName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
                    cost.setOrganizationId(SecurityUtils.getOrgId());
                    cost.setOrganizationName(SecurityUtils.getOrgName());
                    cost.setBelongTo(SecurityUtils.getOrgId().toString());
                    cost.setBudgetAmount(budgetList.get(i).getExpenseAmount());
                    cost.setCostList(budgetList.get(i).getExpenseName());
                    cost.setGenerateTime(new Timestamp(new Date().getTime()));
                    costControlMapper.insertCostControl(cost);
                }
            }

        }
        if ("3".equals(projectReviewInfo.getReviewResult())) {
            ProjectInfo projectInfo = projectInfoMapper.selectProjectInfoByProjectId(projectReviewInfo.getProjectId());
            projectInfo.setState("5");
            projectInfo.setSign("3");
            projectInfo.setContractReviewer(null);
            projectInfo.setCovenantId(null);
            projectInfoMapper.updateProjectInfo(projectInfo);
            SubProjectInfo info = new SubProjectInfo();
            info.setProjectId(projectReviewInfo.getProjectId());
            List<SubProjectInfo> projectInfoList = subProjectInfoMapper.selectSubProjectInfoList(info);
            for (int i = 0; i < projectInfoList.size(); i++) {
                SubProjectInfo subProjectInfo = projectInfoList.get(i);
                subProjectInfo.setState("5");
                subProjectInfoMapper.updateSubProjectInfo(subProjectInfo);
            }
        }
        return count;
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param projectReviewInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateProjectReviewInfo(ProjectReviewInfo projectReviewInfo) {
        return projectReviewInfoMapper.updateProjectReviewInfo(projectReviewInfo);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param reviewIds 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteProjectReviewInfoByReviewIds(String[] reviewIds) {
        return projectReviewInfoMapper.deleteProjectReviewInfoByReviewIds(reviewIds);
    }

    @Override
    public int deleteContractReviewInfoByProjectId(String projectId) {
        return projectReviewInfoMapper.deleteContractReviewInfoByProjectId(projectId);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param reviewId 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteProjectReviewInfoByReviewId(String reviewId) {
        return projectReviewInfoMapper.deleteProjectReviewInfoByReviewId(reviewId);
    }

    private String getTicketIdByTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        int sum = (int) ((Math.random() * 9 + 1) * 100000);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(newDate);
        stringBuilder.append(sum);
        return stringBuilder.toString();
    }
}
